package com.yueke.common.core.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @program: yueke-parent
 * @description: 生成解析JWT
 * @author: XiYang
 * @create: 2020-10-10 14:37
 **/
public class JwtUtil {
    static String secret = "thisisxiyangpasswordthisisxiyangpasswordthisisxiyangpasswordthisisxiyangpassword";

    /**
     * 生成 JWT
     * @param body 用户信息
     * @param minute 过期时间（分钟数）
     * @return Jwt字符串
     */
    public static String creatToken(Map<String, Object> body, Integer minute) {

        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + minute * 60 * 1000))
                .signWith(key)
                .compact();
    }

    /**
     * 解析 JWT
     * @param token Jwt字符串
     * @return Claims对象
     */
    public static Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }
}
